import sys
import os
from time import sleep

import pygame

from alien import Alien
from bullet import Bullet
from sound import Sound


def check_events(settings, screen, ship, bullets, play_button, stats, aliens, score_board, sound):
    """监视键盘和鼠标事件"""
    for event in pygame.event.get():
        # 退出
        if event.type == pygame.QUIT:
            # 游戏退出时，将最高分保存到文件里面
            with open("config.ini", 'wb') as f:
                f.write(str(stats.high_score).encode())
            sys.exit()
        # 按下按键
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(settings, screen, event, ship, bullets, sound)
        # 按键弹起
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)
        # 鼠标点击
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            check_play_button(stats, mouse_x, mouse_y, play_button, bullets, aliens, settings, screen, ship, score_board)


def check_play_button(stats, mouse_x, mouse_y, play_button, bullets, aliens, settings, screen, ship, score_board):
    """判断点击play按钮"""
    button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
    # 只能游戏处于非活动时才能点击play按钮
    if button_clicked and not stats.game_active:
        # 隐藏光标
        pygame.mouse.set_visible(False)
        # 新游戏开始时，需重置游戏设置
        settings.initialize_dynamic_settings()
        # 重置游戏统计信息
        stats.reset_stats()
        stats.game_active = True
        # 重置计分板
        score_board.pre_score()
        score_board.pre_high_score()
        score_board.pre_level()
        score_board.pre_ships()

        # 清空aliens 和 bullet
        aliens.empty()
        bullets.empty()
        # 创建新的aliens
        create_fleet(settings, screen, aliens, ship)
        # ship 居中
        ship.center_ship()


def check_keydown_events(ai_settings, screen, event, ship, bullets, sound):
    """按下按键"""
    if event.key == pygame.K_RIGHT:
        ship.move_right = True
    elif event.key == pygame.K_LEFT:
        ship.move_left = True
    elif event.key == pygame.K_UP:
        ship.move_up = True
    elif event.key == pygame.K_DOWN:
        ship.move_down = True
    elif event.key == pygame.K_SPACE:
        # 按下空格键生成子弹
        fire_bullet(ai_settings, bullets, ship, screen, sound)


def check_keyup_events(event, ship):
    """按键弹起"""
    if event.key == pygame.K_RIGHT:
        ship.move_right = False
    elif event.key == pygame.K_LEFT:
        ship.move_left = False
    elif event.key == pygame.K_UP:
        ship.move_up = False
    elif event.key == pygame.K_DOWN:
        ship.move_down = False


def update_screen(screen, settings, ship, bullets, aliens, play_button, stats, score_board):
    """屏幕更新"""
    # 背景色
    screen.fill(settings.bg_color)

    # 重绘所有子弹的位置
    for bullet in bullets:
        bullet.draw_bullet()

    # 显示飞船位置
    ship.blitme()
    # 将aliens编组绘制到屏幕
    aliens.draw(screen)

    # 显示得分板
    score_board.show_score()

    # 如果游戏处于非激活状态，就显示play按钮
    if not stats.game_active:
        play_button.draw_button()

    # 屏幕可见
    pygame.display.flip()


def update_bullet(bullets, aliens, settings, screen, ship, stats, score_board):
    """更新子弹位置并删除消失的子弹"""
    # 子弹向上移动
    bullets.update()
    # 删除消失的子弹
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)

    check_bullet_alien_collisions(settings, screen, aliens, ship, bullets, stats, score_board)


def check_bullet_alien_collisions(settings, screen, aliens, ship, bullets, stats, score_board):
    """子弹和aliens发生碰撞后清理"""
    # 检查子弹是否打中alien，同时会删除碰撞的子弹和alien
    # sprite.groupcollide() 检测两个编组的成员之间的碰撞。
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
    # 与外星人碰撞的子弹都是字典collisions 中的一个键；而与每颗子弹相关的值都是一个列表，其中包含该子弹撞到的外星人。
    # 我们遍历字典collisions ，确保将消灭的每个外星人的点数都记入得分：
    # 击落alien，统计得分
    if collisions:
        for aliens in collisions.values():
            stats.score += settings.alien_points
            score_board.pre_score()
        # 检查是否是最高得分
        check_high_score(stats, score_board)

    # 检验aliens是否被消灭完了，完了就重新创建一组
    if len(aliens) == 0:
        # 清空子弹
        bullets.empty()
        # 加速
        settings.increase_speed()
        # 设置游戏等级
        stats.level += 1
        score_board.pre_level()

        create_fleet(settings, screen, aliens, ship)


def check_high_score(stats, score_board):
    """检查最高得分记录"""
    if stats.score > stats.high_score:
        stats.high_score = stats.score
        score_board.show_score()


def fire_bullet(ai_settings, bullets, ship, screen, sound):
    """按下空格键生成子弹"""
    # 子弹数量限制
    if len(bullets) <= ai_settings.bullet_limit:
        # 加载射击音效
        sound.play_shoot_sound()
        new_bullet = Bullet(ai_settings, ship, screen)
        bullets.add(new_bullet)


def create_fleet(ai_settings, screen, aliens, ship):
    """创建外星人群"""
    # 创建一个外星人，并计算一行可容纳多少个外星人
    # 外星人间距为外星人宽度
    alien = Alien(ai_settings, screen)
    # 计算每行创建最多的alien数目
    alien_num = get_number_alien_x(ai_settings, alien.rect.width)
    # 计算创建最大行数
    number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height)
    # 创建alien
    for row_number in range(number_rows):
        for i in range(alien_num):
            create_alien(ai_settings, screen, i, aliens, row_number)


def get_number_alien_x(ai_settings, alien_width):
    """计算每行alien数量"""
    available_space_x = ai_settings.screen_width - 3 * alien_width
    alien_num = int(available_space_x / (3 * alien_width))
    return alien_num


def create_alien(ai_settings, screen, i, aliens, row_number):
    """创建alien并加入到编组"""
    alien = Alien(ai_settings, screen)
    alien_width = alien.rect.width
    alien.x = alien_width + 3 * alien_width * i
    alien.rect.x = alien.x
    alien.rect.y = (alien.rect.height + 80) + 3 * alien.rect.height * row_number
    aliens.add(alien)


def get_number_rows(ai_settings, ship_height, alien_height):
    """创建alien的最大行数"""
    available_space_y = ai_settings.screen_height - 4 * alien_height - ship_height
    row_number = int(available_space_y / (4 * alien_height))
    return row_number


def update_alien(settings, aliens, ship, stats, screen, bullets, score_board):
    """alien群移动"""
    # 判断是否达到屏幕边缘
    check_fleet_edges(settings, aliens)
    aliens.update()
    # 检查aliens和ship是否发生碰撞
    # 方法spritecollideany() 接受两个实参：一个精灵和一个编组。
    # 它检查编组是否有成员与精灵发生了碰撞，并在找到与精灵发生了碰撞的成员后就停止遍历编组
    if pygame.sprite.spritecollideany(ship, aliens):
        # print("Ship hit !!!")
        ship_hit(settings, stats, screen, ship, aliens, bullets, score_board)

    # 检查aliens是否和屏幕底端碰撞
    check_aliens_bottom(settings, stats, screen, ship, aliens, bullets, score_board)


def check_fleet_edges(settings, aliens):
    """判断aliens是否到达边缘"""
    for alien in aliens.sprites():
        if alien.check_edges():
            alien.rect.y += settings.fleet_drop_speed
            alien.speed *= -1


def ship_hit(settings, stats, screen, ship, aliens, bullets, score_board):
    """aliens撞到ship后的游戏统计"""
    if stats.ship_left > 0:
        # 飞船生存数减1
        stats.ship_left -= 1
        # 更新剩余飞船数量
        score_board.pre_ships()

        # 清空aliens和bullets列表
        aliens.empty()
        bullets.empty()
        # 重新创建aliens
        create_fleet(settings, screen, aliens, ship)
        # ship居中
        ship.center_ship()
        sleep(1)
    else:
        stats.game_active = False
        pygame.mouse.set_visible(True)


def check_aliens_bottom(settings, stats, screen, ship, aliens, bullets, score_board):
    """检查aliens是否到达屏幕底端"""
    screen_rect = screen.get_rect()
    for alien in aliens.sprites():
        if alien.rect.bottom >= screen_rect.bottom:
            ship_hit(settings, stats, screen, ship, aliens, bullets, score_board)
            break
